package com.kingtone.rongji;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.Header;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.kingtone.rongji.adapter.OrdeDetailProudctAdapter;
import com.kingtone.rongji.biz.OrderDetail;
import com.kingtone.rongji.biz.Product;
import com.kingtone.rongji.biz.ShippingLogInfo;
import com.kingtone.rongji.tool.AppContasts;
import com.kingtone.rongji.tool.RongJiRestClient;
import com.kingtone.rongji.tool.RongJiUtils;
import com.kingtone.rongji.tool.SharedPreferencesUtil;
import com.kingtone.rongji.ui.CancelOrderDialog;
import com.kingtone.rongji.ui.NoScrollListview;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class OrderDetailActivity extends BaseActivity {

	private TextView title = null;
	private ImageView backBtn = null;
	private ImageView leftIcon = null;
	private TextView rightTitle = null;
	private NoScrollListview productListView = null;
	private NoScrollListview sendListView = null;
	
	//取消订单
	private Button cancelOrderBtn = null;
	//立即支付
	private Button payBtn = null;
	//页面元素定义
	
	//基本信息
	private TextView orderNo = null; //订单编号
	private TextView orderStatus = null; //状态
	private TextView payDate = null; //下单日期
	private TextView customerComments = null;//客户备注
	
	//收货信息
	private TextView orderReiver = null; //收货人
	private TextView orderPhone = null; //手机
	private TextView orderArea = null; //地区
	private TextView orderAddress = null;//地址
	
	//支付方式
	private TextView orderPayMethod = null; //支付方式
	private TextView orderSendMethod = null; //配送方式
	private TextView orderWaybillNo= null; //运单号码
	
	private String orderNum = null;
	private OrderDetail orderDetail = null;
	
	private TextView orderTotalAmount = null; //小计
	private TextView shippingCharge = null; //运费
	private TextView discountAmount = null;//订单折扣
	private TextView orderGiftCardAmount = null; //积分抵扣
	private TextView orderExpensePoint = null; //余额抵扣
	private TextView orderPayAmount = null; //应付金额
	
	@Override
	protected void onCreate(Bundle paramBundle)
	{
		super.onCreate(paramBundle);
		this.mContext = this;
		this.setContentView(R.layout.activity_order_detail);
		Intent intent = getIntent();
		if(intent.hasExtra("orderNum"))
		{
			orderNum = intent.getStringExtra("orderNum");
		}		
		if(!TextUtils.isEmpty(orderNum))
		{
			getOrderDetail(orderNum);
		}
		setupView();
	}
	
	private void setupView()
	{
		title = (TextView)findViewById(R.id.title);
		title.setText(getString(R.string.order_detail_title));
		backBtn = (ImageView)findViewById(R.id.back);
		backBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				onBackPressed();
			}
		});
		
		leftIcon = (ImageView)findViewById(R.id.left_icon);
		leftIcon.setBackgroundResource(R.drawable.icon_zhang);
		
		rightTitle = (TextView)findViewById(R.id.right_title);
		rightTitle.setText(getString(R.string.order_detail_title));
		
		//基本信息
		orderNo = (TextView)findViewById(R.id.order_detail_no);
		orderStatus = (TextView)findViewById(R.id.order_detail_status);
		payDate = (TextView)findViewById(R.id.order_detail_date);
		customerComments = (TextView)findViewById(R.id.order_detail_customer_comments);
		
		//收货信息
		orderReiver = (TextView)findViewById(R.id.order_detail_reciver);
		orderPhone = (TextView)findViewById(R.id.order_detail_phone);	
		orderArea = (TextView)findViewById(R.id.order_detail_area);
		orderAddress = (TextView)findViewById(R.id.order_detail_address);
		
		//支付方式
		orderPayMethod = (TextView)findViewById(R.id.order_detail_pay_method);
		orderSendMethod = (TextView)findViewById(R.id.order_detail_send_method);
		orderWaybillNo = (TextView)findViewById(R.id.order_detail_waybill);
		
		productListView = (NoScrollListview)findViewById(R.id.order_detail_products_list);
		
		
		sendListView = (NoScrollListview)findViewById(R.id.order_detail_send_list);
		
		orderTotalAmount = (TextView)findViewById(R.id.order_detail_total_amount);
		shippingCharge = (TextView)findViewById(R.id.order_detail_shipping_charge);
		orderGiftCardAmount = (TextView)findViewById(R.id.order_detail_jifen_discount);
		discountAmount = (TextView)findViewById(R.id.order_detail_discount);
		orderExpensePoint = (TextView)findViewById(R.id.order_detail_total_discount);
		orderPayAmount = (TextView)findViewById(R.id.order_detail_total_price);
		
		payBtn = (Button)findViewById(R.id.order_detail_pay_now);
		cancelOrderBtn = (Button)findViewById(R.id.order_detail_cancel_order);
		
	}
	
	private void initData()
	{
		if(orderDetail != null)
		{
			//基本信息
			orderNo.setText(getString(R.string.order_no) + orderDetail.getOrderNumber());
			orderStatus.setText(RongJiUtils.getOrderStatusStr(orderDetail.getOrderStatus()));
			payDate.setText(getString(R.string.order_date) + RongJiUtils.revertDate(orderDetail.getOrderDate()));
			
			customerComments.setText(getString(R.string.order_detail_customer_comments) + orderDetail.getUserMemo());
			
			//收货信息
			orderReiver.setText(getString(R.string.order_detail_reciver) + orderDetail.getCustomerUserName());
			orderPhone.setText(getString(R.string.order_detail_phone) + orderDetail.getReceiveCellPhone());
			String regionName = orderDetail.getRegionName() == null ? "" : orderDetail.getRegionName();
			orderArea.setText(getString(R.string.order_detail_area) + regionName);
			orderAddress.setText(getString(R.string.order_detail_address) + orderDetail.getReceiveAddress());
			
			//支付方式
			int arrivePay = orderDetail.getArrivePay();
			String arrivePayStr = getString(R.string.detail_not_cod);
			if(arrivePay == 1)
			{
				arrivePayStr = getString(R.string.detail_cod);
			}
			orderPayMethod.setText(getString(R.string.order_detail_pay_method) + arrivePayStr);
			orderSendMethod.setText(getString(R.string.order_detail_send_method) + orderDetail.getShippingModeName());
			String shipOrderNum = orderDetail.getShipOrderNumber() == null ? "" : orderDetail.getShipOrderNumber();
			orderWaybillNo.setText(getString(R.string.order_detail_waybill_no) + shipOrderNum);

			ArrayList<Product> productList = orderDetail.getProductList();
			if(productList != null)
			{
				OrdeDetailProudctAdapter adapter = new OrdeDetailProudctAdapter(mContext, productList);
				productListView.setAdapter(adapter);
			}
		    
			List<Map<String, String>> sendList = new ArrayList<Map<String, String>>();
			Map<String, String> map = new HashMap<String, String>();  
			map.put("time",getString(R.string.process_time));  
			map.put("info", getString(R.string.process_info));  
	        sendList.add(map);  
	        ArrayList<ShippingLogInfo> shippingInfoList = orderDetail.getShippingInfoList();
	        if(shippingInfoList != null && shippingInfoList.size() > 0)
	        {
	        	for(ShippingLogInfo info:shippingInfoList)
	        	{
	        		Map<String, String> shippingMap = new HashMap<String, String>();
	        		shippingMap.put("time", RongJiUtils.revertDate(info.getProcessTime()));
	        		shippingMap.put("info", info.getProcessInfo());
	        		sendList.add(shippingMap);  
	        	} 
	        }
	        
			SimpleAdapter chat = new SimpleAdapter(mContext, sendList, R.layout.send_info,  
	                new String[] {"time","info"}, new int[] {R.id.send_process_time,R.id.send_process_info});  
			sendListView.setAdapter(chat);  
		
			orderTotalAmount.setText(""+orderDetail.getOrderTotalAmount());
			shippingCharge.setText(""+orderDetail.getShippingCharge());
			discountAmount.setText(""+orderDetail.getDiscountAmount());
			orderGiftCardAmount.setText(""+orderDetail.getOrderGiftCardAmount());
			orderExpensePoint.setText(""+orderDetail.getOrderExpensePoint());
			orderPayAmount.setText(""+orderDetail.getOrderPayAmount());
			
			if(orderDetail.getOrderStatus() == 1) //待支付
			{
				payBtn.setVisibility(View.VISIBLE);
				payBtn.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						
						Intent intent = new Intent(mContext, PayNoticeActivity.class);
						intent.putExtra("orderNo", orderDetail.getOrderNumber());
						String subject = getString(R.string.welcome_img) +"_"+ orderDetail.getOrderNumber();
						intent.putExtra("subject", subject);
						String cutsomer = orderDetail.getCustomerUserName();
						if(TextUtils.isEmpty(cutsomer))
						{
							cutsomer = SharedPreferencesUtil.getInstance(mContext).getString(AppContasts.USERNAME_KEY);
						}
						if(!TextUtils.isEmpty(cutsomer))
						{
							cutsomer  = cutsomer + "_";
						}
						intent.putExtra("body", cutsomer  + orderDetail.getOrderNumber());
						intent.putExtra("payAmount", orderDetail.getOrderPayAmount());
						startActivity(intent);
					}
				});
			}else
			{
				payBtn.setVisibility(View.GONE);
			}
			
			if(orderDetail.getOrderStatus() < 2) //未支付状态
			{
				cancelOrderBtn.setVisibility(View.VISIBLE);
				cancelOrderBtn.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						Dialog dialog = CancelOrderDialog.show(mContext, orderNum, new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								CancelOrderDialog.dismiss();
								
							}
						});
					dialog.show();
					}
				});
				
			}else
			{
				cancelOrderBtn.setVisibility(View.GONE);
			}
		}
			
	}
	
	
	/**
	 * 获取订单详情
	 * @param orderNumber
	 */
	private void getOrderDetail(String orderNumber)
	{
		RongJiRestClient.getOrderDetail(orderNumber, new AsyncHttpResponseHandler() {

			@Override
			public void onStart() {
				RongJiUtils.showEmptyProgress(mContext);
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
			    if(arg2 != null)
			    {
			    	String filureStr = new String(arg2);
					Log.d("failure", filureStr);
			    }
				RongJiUtils.dismissProgress();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				
				RongJiUtils.dismissProgress();
				
				if(arg2 != null && !new String(arg2).equalsIgnoreCase("null"))
				{
					String result = new String(arg2);
					Gson gson = new Gson();
					JsonParser parser = new JsonParser();
					JsonElement elment = parser.parse(result);
					orderDetail = gson.fromJson(elment, OrderDetail.class);
					initData();
				}
			}	
		});
	}
	
}
